<template>
  <view class="login" hover-class="none" hover-stop-propagation="false">
    <view class="login-content" hover-class="none" hover-stop-propagation="false">
      <image class="login-icon" src="@/static/logo.png" />
      <u-gap height="40rpx"></u-gap>
      <view class="login-title"> 云瞳登录 </view>
      <view class="login-form" hover-class="none" hover-stop-propagation="false">
        <u-form ref="loginForm" :model="loginForm" errorType="toast">
          <u-form-item prop="account">
            <u-input
              v-model="loginForm.account"
              prefixIcon="account"
              prefixIconStyle="font-size: 30rpx;color: #000000"
              placeholderStyle="color: #797D8C;"
              placeholder="请输入帐号"
              :customStyle="customStyle_"
              border="none"
            ></u-input>
          </u-form-item>
          <u-form-item prop="password">
            <u-input
              v-model="loginForm.password"
              :password="!openEye"
              prefixIcon="lock"
              prefixIconStyle="font-size: 30rpx; color: #000000"
              placeholderStyle="color: #797D8C;"
              placeholder="请输入密码"
              :customStyle="customStyle_"
              border="none"
            >
              <u-icon :name="openEye ? 'eye' : 'eye-off'" slot="suffix" size="36" @click="openEye = !openEye"></u-icon>
            </u-input>
          </u-form-item>
          <u-button text="登录" type="primary" loadingMode="circle" shape="circle" @click="handleFormSubmit" :loading="sumbitBtnLoading"></u-button>
          <u-form-item prop="checkPricacy">
            <view class="login-privacy dl-flex dl-flex-ai-center dl-flex-jc-center" hover-class="none" hover-stop-propagation="false">
              <u-checkbox-group v-model="loginForm.checkPricacy" size="32">
                <u-checkbox></u-checkbox>
              </u-checkbox-group>
              <view>阅读并同意<text @click="handleShowModal('test1')">《用户协议》</text>和<text @click="handleShowModal('test2')">《隐私条款》</text></view>
            </view>
          </u-form-item>
        </u-form>
      </view>
    </view>
    <!--  #ifdef MP-WEIXIN -->
    <u-popup :show="popupShow">
      <view class="dl-privacy-popup" hover-class="none" hover-stop-propagation="false">
        <view class="dl-privacy-popup-hd">
          <text class="dl-privacy-popup-title">{{ popupObj.title }}</text>
        </view>
        <view class="dl-privacy-popup-bd">
          <view class="dl-privacy-popup-tips">{{ popupObj.desc1 }}</view>
          <view class="dl-privacy-popup-tips" style="color: blue" @click="openPrivacyContract">{{ urlTitle }}</view>
          <view class="dl-privacy-popup-tips">{{ popupObj.desc2 }}</view>
        </view>
        <view class="dl-privacy-popup-ft">
          <view class="dl-privacy-popup-btn-area">
            <button id="disagree-btn" type="error" class="u-reset-button" @click="handleDisAgree">
              <text>不同意</text>
            </button>
            <button id="agree-btn" type="success" class="u-reset-button" open-type="agreePrivacyAuthorization" @agreeprivacyauthorization="handleAgree">
              <text>同意</text>
            </button>
          </view>
        </view>
      </view>
    </u-popup>
    <!--  #endif -->
    <u-notify ref="uNotify" :customStyle="{ padding: '13px 10px' }"></u-notify>
    <u-modal :show="showModal" :title="modalTitle" :showCancelButton="false" confirm-text="关闭" @confirm="showModal = false">
      <u-parse :content="content"></u-parse>
    </u-modal>
  </view>
</template>

<script>
import { getSystemConfig } from '@/api/login'

let resolvePrivacyAuthorization = null
export default {
  name: 'Login',
  data() {
    const rules = Object.freeze({
      account: {
        type: 'string',
        required: true,
        message: '请填写账号',
        trigger: ['blur', 'change']
      },
      password: {
        type: 'string',
        required: true,
        message: '请填写密码',
        trigger: ['blur', 'change']
      },
      checkPricacy: {
        type: 'array',
        required: true,
        message: '请同意协议',
        validator: (rule, value, callback) => {
          return value.length > 0
        },
        trigger: ['blur', 'change']
      }
    })
    return {
      openEye: false,
      rules,
      showModal: false,
      modalTitle: null,
      content: '《用户服务协议及隐私保护政策》',
      loginForm: {
        account: null,
        password: null,
        checkPricacy: []
      },
      customStyle_: {
        borderRadius: 0,
        borderBottom: '1px solid #b2b4bb',
        padding: '12rpx 2rpx'
      },
      sumbitBtnLoading: false,
      popupShow: false,
      rejected: false,
      urlTitle: '隐私保护指引',
      popupObj: Object.freeze({
        title: '用户隐私保护提示',
        desc1: '感谢您使用本小程序，您使用本小程序前应当阅读井同意',
        desc2: '当您点击同意并开始时用产品服务时，即表示你已理解并同息该条款内容，该条款将对您产生法律约束力。如您拒绝，将无法正常使用小程序。'
      }),
      titleObj: {},
      valueObj: {}
    }
  },
  onReady() {
    this.$refs.loginForm.setRules(this.rules)
  },
  methods: {
    handleFormSubmit() {
      this.sumbitBtnLoading = true
      !this.rejected && this.checkNeedPrivacyAuthorization()
      this.$refs.loginForm
        .validate()
        .then(res => {
          if (res) {
            try {
              this.$store
                .dispatch('permission/login', { username: this.loginForm.account, password: this.loginForm.password, keyid: process.env.VUE_APP_KEY_ID })
                .then(() => {
                  this.$refs.uNotify.show({
                    type: 'success',
                    message: '登录成功'
                  })
                  setTimeout(() => {
                    uni.switchTab({
                      url: '/pages/index/index'
                    })
                  }, 1 * 1000)
                })
                .catch(err => {
                  this.sumbitBtnLoading = false
                })
            } catch (err) {
              this.sumbitBtnLoading = false
            }
          } else {
            this.sumbitBtnLoading = false
          }
        })
        .catch(() => {
          this.sumbitBtnLoading = false
        })
    },
    popUp() {
      if (this.popupShow === false) {
        this.popupShow = true
      }
    },
    disPopUp() {
      if (this.popupShow === true) {
        this.popupShow = false
      }
    },
    openPrivacyContract() {
      // #ifdef MP-WEIXIN
      wx.openPrivacyContract({
        success: () => {
          console.log('openPrivacyContract success')
        },
        fail: res => {
          console.error('openPrivacyContract fail', res)
        }
      })
      // #endif
    },
    handleAgree() {
      resolvePrivacyAuthorization({ buttonId: 'agree-btn', event: 'agree' })
      this.disPopUp()
      this.rejected = false
    },
    handleDisAgree() {
      resolvePrivacyAuthorization({ event: 'disagree' })
      this.rejected = true
      this.disPopUp()
    },
    handleShowModal(type) {
      this.modalTitle = this.titleObj[type]
      this.content = this.valueObj[type]
      this.showModal = true
    },
    checkNeedPrivacyAuthorization() {
      // #ifdef MP-WEIXIN
      if (wx.onNeedPrivacyAuthorization) {
        wx.getPrivacySetting({
          success: res => {
            if (res.needAuthorization) {
              this.rejected = false
              this.urlTitle = res.privacyContractName
              wx.requirePrivacyAuthorize()
            }
          }
        })
        wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
          const referrer = eventInfo?.referrer
          console.log('触发 onNeedPrivacyAuthorization ' + referrer)
          const refers = ['requirePrivacyAuthorize']
          referrer && refers.indexOf(referrer) > -1 && this.popUp()
          resolvePrivacyAuthorization = resolve
        })
      }
      // #endif
    },
    async getSystemConfig_() {
      const { data } = await getSystemConfig()
      const test1 = data.find(i => i.paramterCode === '1004')
      const test2 = data.find(i => i.paramterCode === '1005')
      this.titleObj = {
        test1: test1.paramterName,
        test2: test2.paramterName
      }
      this.valueObj = {
        test1: test1.paramterValue.replaceAll('\n', '<br />'),
        test2: test2.paramterValue.replaceAll('\n', '<br />')
      }
    }
  },
  onLoad() {
    this.checkNeedPrivacyAuthorization()
    // this.getSystemConfig_()
  }
}
</script>

<style lang="scss">
.login {
  height: 100vh;
  background-repeat: no-repeat;
  background-size: cover;
  padding-top: 65rpx;
  padding-bottom: 150rpx;

  &-content {
    position: relative;
    height: calc(100vh - 235rpx);
    text-align: center;
  }

  &-icon {
    display: block;
    width: 200rpx;
    height: 200rpx;
    margin: auto;
  }

  &-title {
    margin: auto;
    font-size: 24px;
    font-weight: 500;
  }

  &-form {
    padding: 155rpx 48rpx 0;
    .u-form {
      &-item {
        padding: 0 32rpx;
        &:last-child {
          position: absolute;
          bottom: 0;
          width: 654rpx;
        }
      }
      .u-input__content {
        &__field-wrapper {
          input {
            font-size: 30rpx !important;
          }
        }
      }
      button {
        margin-top: 30rpx;
        height: 90rpx;
      }
    }
  }

  &-privacy {
    > view {
      .u-checkbox__icon-wrap {
        border-radius: 4rpx !important;
      }
      &:last-child {
        height: 28rpx;
        font-size: 28rpx;
        color: #8f929f;
        line-height: 28rpx;
        text {
          color: #519efe;
        }
      }
    }
  }

  .u-modal__title {
    padding-top: 12px !important;
    padding-bottom: 6px;
  }

  .u-modal__content {
    overflow: scroll;
    max-height: 800rpx;
    padding-top: 6px !important;
  }
}
.dl-privacy-popup {
  padding: 0 48rpx 68rpx;
  &-hd {
    min-height: 128rpx;
    display: flex;
    align-items: center;
    flex-shrink: 0;
  }
  &-bd {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    word-wrap: break-word;
    hyphens: auto;
    padding-bottom: 112rpx;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.9);
  }
  &-tips {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.3);
    line-height: 1.4;
    &:not(:first-child) {
      padding-top: 32rpx;
    }
  }
  &-ft {
    text-align: center;
  }
  &-btn-area {
    display: flex;
    align-items: center;
    justify-content: center;

    button {
      width: 100%;
      font-weight: 700;
      font-size: 28rpx;
      text-align: center;
      text-decoration: none;
      border-radius: 6rpx;
      color: #fff;
      border-width: 1px;
      border-style: solid;
      padding: 0 24rpx;
      height: 80rpx;
      position: relative;
      align-items: center;
      justify-content: center;
      display: flex;
      flex-direction: row;
      box-sizing: border-box;
      flex-direction: row;
      &::before {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        height: 100%;
        border: inherit;
        border-radius: inherit;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        opacity: 0;
        content: ' ';
        background-color: #000;
        border-color: #000;
      }
      &:first-child {
        margin-right: 16rpx;
        background-color: #fa3534;
        border-color: #fa3534;
      }
      &:last-child {
        margin-left: 16rpx;
        background-color: #19be6b;
        border-color: #19be6b;
      }
    }
  }
}
</style>
